﻿using System.Threading;
using System.Net.Sockets;
using System;
using System.Text;

namespace DroidPad
{
    class wifiConn
    {
        private const int MAX_MESSAGE_SIZE = 2048;
        private TcpListener tc;
        private NetworkStream ns;
        private Socket tc2;
        private bool listening = true;
        private Thread connThread,oldThread=null;
        private Delegate readDataCallback, connectionClosedCallback;
        private byte[] m = new byte[MAX_MESSAGE_SIZE];
        private int bytesread;
        private ASCIIEncoding asciiE=new ASCIIEncoding();

        public wifiConn(Delegate func1, Delegate func2)
        {
           // try { 
                tc = new TcpListener(Properties.Settings.Default.Port);
            readDataCallback = func1;
            connectionClosedCallback = func2;
           // }
          //  catch { DPsf.SendErrorMessage("Could not connect."); return; }
        }

        private string readData(int BufferLen)
        {
          //  try
           // {
                bytesread = ns.Read(m, 0, BufferLen);
                
            //}
            //catch
            //{
               // DPsf.SendErrorMessage("Socket error.");
                //return null;
            //}
            if (bytesread == 0)
            {
                DPsf.SendStatMessage("Disconnected...");
                tc2.Close();
                ns.Close();
                return null;
            }
            return asciiE.GetString(m, 0, bytesread);
        }

        private void receiveLoop()
        {
           // if (oldThread != null) oldThread.Abort();
            String strReceived;
            tc2 = tc.AcceptSocket();
            DPsf.SendStatMessage("Connected-wifi");
            ns = new NetworkStream(tc2);

            strReceived = readData(MAX_MESSAGE_SIZE);
            while (listening)
            {
                if (!tc2.Connected)
                {
                    DPsf.SendStatMessage("Disconnected...");
                    oldThread = connThread;
                    connectionClosedCallback.DynamicInvoke();
                    oldThread.Abort();
                    //break;
                }
                if (strReceived != "")
                {
                    readDataCallback.DynamicInvoke(new object[] { connHandler.ConnType.WiFi, strReceived });
                    strReceived = readData(MAX_MESSAGE_SIZE);
                }
            }
        }

        public void writeData(byte[] data, int size)
        {
            ns.Write(data,0,size);
        }

        public void stop()
        {
            listening = false;
            if (tc2 != null)
            {
                ns.Close();
                tc2.Close();
            }
            tc.Stop();
        }

        public void close()
        {
            connThread.Abort();
            stop();
        }

        public void start()  
        {
            listening = true;
            tc.Start();
            //oldThread = connThread;
            connThread = new Thread(new ThreadStart(delegate() { receiveLoop(); }));
            connThread.Start();
        }
    }
}
